<template>
  <lay-card>
    <lay-form :model="user_info_cur" :rules="rules">
      <lay-form-item label="用户工号">
        <lay-input v-model="user_info_cur.user_no" disabled></lay-input>
      </lay-form-item>
      <lay-form-item label="用户姓名" prop="username">
        <lay-input v-model="user_info_cur.username" :disabled="readFlag"></lay-input>
      </lay-form-item>
      <lay-form-item label="用户邮箱" prop="email">
        <lay-input v-model="user_info_cur.email" :disabled="readFlag"></lay-input>
      </lay-form-item>
      <lay-form-item label="所选产品" mode="inline">
        <lay-select v-model="user_info_cur.products" :disabled="readFlag" :multiple="true">
          <lay-select-option :value="item.id" :label="item.name" v-for="item in groups"></lay-select-option>
        </lay-select>
      </lay-form-item>
      <lay-form-item style="text-align: center;">
        <lay-button type="normal" :fluid="true" @click="viewUserInfo" style="width: 120px">
          {{ readFlag === true ? '编辑': '提交修改' }}
        </lay-button>
      </lay-form-item>
    </lay-form>
    <lay-line id="error_message">{{error_message}}</lay-line>
  </lay-card>
</template>

<script lang="ts">
export default {
    name: "userInfos"
}
</script>

<script lang="ts" setup>
import {onMounted, reactive, ref} from "vue";
import {getProducts, updateUser} from "../../api/module/user";
import {layer} from "@layui/layer-vue";
import {useRouter} from "vue-router";
import {userStore} from "../../store/user";

const router = useRouter();
const user = userStore();
const groups = ref([]);
const error_message = ref("");

const getAllZone = async () => {
    let {result, status, message} = await getProducts({user_no: null});
    if (status == 'success') {
        groups.value = result;
    }else {
        layer.msg(message);
    }
};

const {user_info} = defineProps({
  user_info: {type: Object, default: {}},
})

const user_info_cur = reactive({username: "", user_no: "", email: "", products: [], tenant: ""});

onMounted(() => {
    getAllZone();
    user_info_cur.username = user_info.username;
    user_info_cur.user_no = user_info.user_no;
    user_info_cur.email = user_info.email;
    user_info_cur.products = user_info.products;
    user_info_cur.tenant = user_info.tenant;
})

const rules = ref({
  username : {
    type :  'string',
    min : 2,
    max : 20
  },
  email : {
    type :  'email'
  }
});

const readFlag: any = ref(true);

const viewUserInfo = async () => {
  if(readFlag.value === true){
      readFlag.value = false;
  }else {
      const modifyForm = reactive({username: user_info_cur.username, user_no: user_info_cur.user_no,
          email: user_info_cur.email, products: user_info_cur.products})
      console.log(modifyForm);
      let {result, status, message} = await updateUser(modifyForm);
      error_message.value = message;
      if(status == 'success'){
          readFlag.value = true;
      }
  }
};

</script>

<style scoped>

</style>